from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from meiduo.libs.captcha.captcha import Captcha
from django_redis import get_redis_connection
from .constants import IMAGE_CODE_REDIS_EXPIRES


class ImageCodeAPIView(APIView):
    def get(self, request, image_code_id):
        """
        生成验证码图片
        :param request:
        :param image_code_id: 响应验证码
        :return:
        """
        # 1/生成验证码
        captcha = Captcha()
        text, image = captcha.generate_captcha()
        # 2/保存文本格式验证码到redis数据库
        redis = get_redis_connection('verifys')
        redis.setex('image_{}'.format(image_code_id), IMAGE_CODE_REDIS_EXPIRES, text)

        # 3/返回验证码图片
        return HttpResponse(image, content_type="images/jpg")
